package org.linlinjava.litemall.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.linlinjava.litemall.db.dao.GrouponRulesMapper;
import org.linlinjava.litemall.db.models.GrouponRules;
import org.linlinjava.litemall.db.service.GrouponRulesService;
import org.linlinjava.litemall.db.util.GrouponConstant;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class GrouponRulesServiceImpl extends ServiceImpl<GrouponRulesMapper, GrouponRules>
        implements GrouponRulesService {

    /**
     * 查询某个商品关联的团购规则
     *
     * @param goodsId
     * @return
     */
    public List<GrouponRules> queryByGoodsId(Long goodsId) {
        QueryWrapper<GrouponRules> query = new QueryWrapper<>();
        query.eq("goods_id", goodsId);
        query.eq("status",GrouponConstant.RULE_STATUS_ON);
        return baseMapper.selectList(query);
    }

    public int countByGoodsId(Long goodsId) {
        return this.queryByGoodsId(goodsId).size();
    }

    public List<GrouponRules> queryByStatus(Short status) {
        QueryWrapper<GrouponRules> query = new QueryWrapper<>();
        query.eq("status", status);
        return baseMapper.selectList(query);
    }


    public IPage<GrouponRules> queryList(Integer pageNo, Integer pageSize) {
        QueryWrapper<GrouponRules> query = new QueryWrapper<>();
        Page<GrouponRules> page = new Page<>(pageNo, pageSize);
        query.eq("status", GrouponConstant.RULE_STATUS_ON);
        query.orderByDesc("add_time");
        return baseMapper.selectPage(page, query);
    }

    /**
     * 判断某个团购规则是否已经过期
     *
     * @return
     */
    public boolean isExpired(GrouponRules rules) {
        return (rules == null || rules.getExpireTime().isBefore(LocalDateTime.now()));
    }

    /**
     * 获取团购规则列表
     *
     * @param goodsId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public IPage<GrouponRules> querySelective(String goodsId, Integer pageNo, Integer pageSize) {
        QueryWrapper<GrouponRules> query = new QueryWrapper<>();
        Page<GrouponRules> page = new Page<>(pageNo, pageSize);
        query.eq("status", GrouponConstant.RULE_STATUS_ON);
        query.eq(!StringUtils.isEmpty(goodsId), "goods_id", goodsId);
        return baseMapper.selectPage(page, query);
    }

}